package uf.audit.db;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import uf.audit.util.Consts;
import uf.audit.util.Table;

/**
 * 权限实体
 * 
 * @author sunny
 *
 */

@Table(key = "authbh")
public class Authentic extends Model<Authentic> {
	private static final long serialVersionUID = -7644540082576539659L;
	public static Authentic dao = new Authentic().use(DbKit.MAIN_CONFIG_NAME);

	// 容错处理 如果set的值为空，就不做处理
	public Authentic set(String attr, Object value) {
		if (value != null) {
			super.set(attr, value);
		}
		return this;
	}

	// 根据类型和编号（resource）删除指定记录
	public void deleteWithResourceBh(String bh, int type) {
		if (bh == null)
			DbPro.use().update("delete from authentic where authvalue=?", type);
		else
			DbPro.use().update("delete from authentic where authvalue=? and resourcebh=?", type, bh);
	}

	// 获取某个用户所有的权限信息
	public List<Integer> getuserauth(String userbh) {
		List<Record> recs = DbPro.use().find("select distinct(authvalue) as authvalue from authentic where userbh=?",
				userbh);
		List<Integer> result = new ArrayList<Integer>();
		for (Record rec : recs) {
			Integer i = rec.getInt("authvalue");
			result.add(i);
		}
		return result;
	}

	// 更新
	public boolean update(JSONObject obj) {
		String bh = obj.getString("authbh");
		Authentic item = new Authentic();
		item.set("userbh", obj.getString("userbh"));
		item.set("resourcebh", obj.getString("resourcebh"));
		item.set("authvalue", obj.getInteger("authvalue"));
		boolean result = false;
		if (bh != null) {
			item.set("authbh", bh);
			result = item.update();
		} else {
			item.set("authbh", UUID.randomUUID().toString());
			result = item.save();
		}
		return result;
	}

	// 删除
	public boolean delete(String bh) {
		return deleteById(bh);
	}

	// 校验某个用户是否有某个试卷的考试权限
	public boolean checkTestAuthentic(String modelbh, String userbh) {
		return checkAuthentic(modelbh, userbh, Consts.AUTH_TEST);
	}

	// 校验某个用户是否有某个试卷的阅卷权限
	public boolean checkMarkingAuthentic(String modelbh, String userbh) {
		return checkAuthentic(modelbh, userbh, Consts.AUTH_MARKING);
	}

	// 校验某个用户是否有某个试卷的某个权限
	public boolean checkAuthentic(String modelbh, String userbh, int type) {
		String sql = "select * from authentic where userbh=? and resourcebh=? and authvalue=?";
		Authentic a = findFirst(sql, userbh, modelbh, type);
		if (a == null)
			return false;
		return true;
	}
}
